package ic

import (
	"bytes"
	"fmt"
	"image"
	"image/png"
)

type PNGConverter struct{}

func (p *PNGConverter) SupportedFormat() string {
	return "PNG"
}

func (p *PNGConverter) FileExtension() string {
	return ".png"
}

func (p *PNGConverter) MimeType() string {
	return "image/png"
}

func (p *PNGConverter) Encode(img image.Image, options ...Options) ([]byte, error) {
	var buf bytes.Buffer

	// 合并选项
	opts := MergeOptions(options...)

	// PNG使用压缩级别
	compressionLevel := png.DefaultCompression
	switch {
	case opts.Compress <= 3:
		compressionLevel = png.BestSpeed
	case opts.Compress >= 7:
		compressionLevel = png.BestCompression
	default:
		compressionLevel = png.DefaultCompression
	}

	encoder := png.Encoder{
		CompressionLevel: compressionLevel,
	}

	if err := encoder.Encode(&buf, img); err != nil {
		return nil, fmt.Errorf("PNG编码失败: %v", err)
	}

	return buf.Bytes(), nil
}

func (p *PNGConverter) Decode(data []byte) (image.Image, error) {
	return png.Decode(bytes.NewReader(data))
}
